package com.zerocarbon.declaration.server.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zerocarbon.declaration.common.dto.DeclarationDTO;
import com.zerocarbon.declaration.server.entity.Declaration;
import com.zerocarbon.declaration.server.entity.DeclareAuthor;
import com.zerocarbon.declaration.server.service.DeclarationService;
import com.zerocarbon.declaration.server.service.DeclareAuthorService;
import com.zerocarbon.framework.common.result.Result;
import com.zerocarbon.framework.web.extension.ValidRestAuth;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @类名: DeclarationController
 * @描述:
 * @作者:
 * @日期: 2021/6/26 15:07
 */
@RequestMapping("/declaration")
@RestController
@ValidRestAuth
public class DeclarationController {

    @Autowired
    private DeclarationService declarationService;
    @Autowired
    private DeclareAuthorService declareAuthorService;
    @Value("${declaration.filePath}")
    private String defaultFilePath;

    /**
     * 保存或提交申报
     * @param dto
     * @return
     */
    @CrossOrigin(originPatterns = "*",allowCredentials="true",allowedHeaders = "*",methods = {})
    @PostMapping("/subscribe")
    public Result subscribe(@Validated @RequestBody DeclarationDTO dto) {
        //每个用户只能提交一次
        Assert.notNull(dto.getAccount());
        Declaration declaration = new Declaration();
        declaration.setAccount(dto.getAccount());
        Declaration declarationHistory = declarationService.getOne(new QueryWrapper<Declaration>(declaration).last("limit 1"));
        if (declarationHistory != null){
            return Result.success();
        }
        declaration.setSaveType(dto.getSaveType());
        declarationService.save(declaration);
        return Result.success();
    }

    /**
     * 保存或提交申报
     * @param dto
     * @return
     */
    @CrossOrigin(originPatterns = "*",allowCredentials="true",allowedHeaders = "*",methods = {})
    @PostMapping("/add")
    public Result add(@Validated @RequestBody DeclarationDTO dto) {
        //每个用户只能提交一次
        Assert.notNull(dto.getAccount());
        Declaration declaration = new Declaration();
        declaration.setAccount(dto.getAccount());
        Declaration declarationHistory = declarationService.getOne(new QueryWrapper<Declaration>(declaration).last("limit 1"));
        if (declarationHistory != null){
            if (declarationHistory.getSaveType() != null && declarationHistory.getSaveType() ==1){
                return Result.fail("申报已经提交，不可修改");
            }
            declarationService.removeById(declarationHistory.getId());
            Map map = new HashMap();
            map.put("declaration_id",declarationHistory.getId());
            declareAuthorService.removeByMap(map);
        }
        BeanUtils.copyProperties(dto,declaration);
        boolean saveSuccess = declarationService.save(declaration);
        if (saveSuccess){
            if (!CollectionUtils.isEmpty(dto.getDeclareAuthors())){
                Long declarationId = declaration.getId();
                for (int i = 0; i < dto.getDeclareAuthors().size(); i++) {
                    DeclareAuthor declareAuthor = dto.getDeclareAuthors().get(i);
                    declareAuthor.setDeclarationId(declarationId);
                    declareAuthorService.save(declareAuthor);
                }
            }
        }
        return Result.success();
    }

    /**
     * 编辑申报草稿
     * @param dto
     * @return
     */
    @CrossOrigin(originPatterns = "*",allowCredentials="true",allowedHeaders = "*",methods = {})
    @PostMapping("/update")
    public Result update(@Validated @RequestBody DeclarationDTO dto) {
        //每个用户只能提交一次
        Declaration declarationHistory = declarationService.getById(dto.getId());
        if (declarationHistory != null){
            if (declarationHistory.getSaveType() != null && declarationHistory.getSaveType() ==1){
                return Result.fail("申报已经提交，不可修改");
            }
            Map map = new HashMap();
            map.put("declaration_id",declarationHistory.getId());
            declareAuthorService.removeByMap(map);
            BeanUtils.copyProperties(dto,declarationHistory);
            declarationService.updateById(declarationHistory);
            if (!CollectionUtils.isEmpty(dto.getDeclareAuthors())){
                Long declarationId = declarationHistory.getId();
                for (int i = 0; i < dto.getDeclareAuthors().size(); i++) {
                    DeclareAuthor declareAuthor = dto.getDeclareAuthors().get(i);
                    declareAuthor.setDeclarationId(declarationId);
                    declareAuthorService.save(declareAuthor);
                }
            }
            return Result.success();
        }
        Declaration declaration = new Declaration();
        BeanUtils.copyProperties(dto,declaration);
        boolean saveSuccess = declarationService.save(declaration);
        if (saveSuccess){
            if (!CollectionUtils.isEmpty(dto.getDeclareAuthors())){
                Long declarationId = declaration.getId();
                for (int i = 0; i < dto.getDeclareAuthors().size(); i++) {
                    DeclareAuthor declareAuthor = dto.getDeclareAuthors().get(i);
                    declareAuthor.setDeclarationId(declarationId);
                    declareAuthorService.save(declareAuthor);
                }
            }
        }
        return Result.success();
    }

    /**
     * 查看申报
     * @param account
     * @return
     */
    @CrossOrigin(originPatterns = "*",allowCredentials="true",allowedHeaders = "*",methods = {})
    @GetMapping("/detail")
    @ValidRestAuth
    public Result detail(String account) {
        Assert.notNull(account);
        Declaration declaration = new Declaration();
        declaration.setAccount(account);
        Declaration declarationHistory = declarationService.getOne(new QueryWrapper<Declaration>(declaration).last("limit 1"));
        DeclarationDTO declarationDTO = new DeclarationDTO();
        if (declarationHistory != null){
            BeanUtils.copyProperties(declarationHistory,declarationDTO);
            Map map = new HashMap();
            map.put("declaration_id",declarationHistory.getId());
            List collection = (List) declareAuthorService.listByMap(map);
            declarationDTO.setDeclareAuthors(collection);
        }
        return Result.success(declarationDTO);
    }

    @CrossOrigin(originPatterns = "*",allowCredentials="true",allowedHeaders = "*",methods = {})
    @PostMapping("/attach/upload")
    public Result upload(@RequestParam(value = "file") MultipartFile file) {
        if (file != null){
            File dest = new File(defaultFilePath + System.currentTimeMillis() + "-" + file.getOriginalFilename());
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return Result.success(dest.getAbsolutePath());
        }
        return Result.success();
    }

    @CrossOrigin(originPatterns = "*",allowCredentials="true",allowedHeaders = "*",methods = {})
    @GetMapping("/attach/delete")
    public Result removeRobot(String filePath) {
        Assert.notNull(filePath);
        if (new File(filePath).exists()){
            new File(filePath).delete();
        }
        return Result.success();
    }
}
